import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

public class ClientThread implements Runnable{
	private Socket client;
	private DatabaseThread db;
	private Server server;
	
	
	public ClientThread(Socket client, DatabaseThread db, Server server) {
		this.client = client;
		this.db = db;
		this.server = server;
	}

	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			String inputLine;
			Parser parser = new Parser();
			
	        while ((inputLine = in.readLine()) != null) {
				inputLine = inputLine.trim();
				parser.parseLine(inputLine);
				
				HashMap<Integer, Station> stations = Server.stations;
				
				if(inputLine.startsWith("</MEASUREMENT>")) {
					Measurement measurement = parser.getMeasurement();
					int stn = measurement.getStn();
					Station station = null;
					if(stations.containsKey(stn) == false) {
						station = new Station(stn);
						stations.put(stn, station);
						System.out.println("New station added: " + stn);
					}
					else {
						station = stations.get(stn);
					}
					
					ArrayList<String> missing = parser.getMissing();
					if(!station.isHistoryFilled()) {
						//Search for station data
						LinkedList<Measurement> results = db.searchStationData(stn, 30);
						if (results == null || results.size() < 30) {
							System.out.println("Not enough values found ( < 30)");
						}
						else {
							for(Measurement m : results) {							
								station.addMeasurement(m);
							}
							Server.stationFiles++;
						}
					}
					
					if(station.isHistoryFilled()) {
						
						
						//Predict missing values
						for(String s : missing) {
							System.out.println("Missing value " + s + " found.");
							station.predict(s, measurement);
							Server.missingValuesCorrected++;	
						}
						//Check 20% off tempratures
						station.checkTemp(measurement, server);	
						
						//add to database and stationhistory
						station.addMeasurement(measurement);
						db.add(measurement);
						System.out.println("Measurement added.");
						Server.measurementsWrittenToFile++;
					}
					else {
						if(missing.isEmpty()) {
							//add to database and stationhistory
							station.addMeasurement(measurement);
							db.add(measurement);
							System.out.println("Measurement added.");
							Server.measurementsWrittenToFile++;
						}
						else {
							System.out.println("Measurement cannot be inserted, there is missing data and there is no history of >= 30");
							Server.droppedMeasurements++;
						}
					}
					
					
				}
				
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
